package com.xb.system.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 图片代理Controller
 * 将图片请求代理到checksystem后端
 */
@RestController
public class ImageProxyController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 代理service图片请求到checksystem后端
     */
    @GetMapping("/profile/service/images/{filename}")
    public ResponseEntity<byte[]> proxyServiceImage(@PathVariable String filename) {
        try {
            // 代理到checksystem后端（本地8081端口）
            String url = "http://localhost:8081/profile/service/images/" + filename;
            
            // 获取图片数据
            ResponseEntity<byte[]> response = restTemplate.getForEntity(url, byte[].class);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            
            // 根据文件扩展名设置Content-Type
            if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
                headers.setContentType(MediaType.IMAGE_JPEG);
            } else if (filename.endsWith(".png")) {
                headers.setContentType(MediaType.IMAGE_PNG);
            } else if (filename.endsWith(".gif")) {
                headers.setContentType(MediaType.IMAGE_GIF);
            } else {
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            }
            
            // 添加缓存控制
            headers.setCacheControl(CacheControl.maxAge(3600, java.util.concurrent.TimeUnit.SECONDS));
            
            return new ResponseEntity<>(response.getBody(), headers, HttpStatus.OK);
            
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}
